如果要實現,不用的url參數將顯示不同的內容,要如何實作呢?
例如
/ 要顯示hello world
/about 要顯示「This is about page.」
/home 要顯示「Welcome to my homepage!」
範例程式碼如下
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
switch (req.url) {
case '/':
res.end('hello world.');
break;
case '/about':
res.end('This is about page.');
break;
case '/home':
res.end('Welcome to my homepage!');
break;
default:
res.end('NotFound!');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
想對外分享這則貼文嗎?運用網址更方便呦~